#include "qKalkulacijakorekcija.h"
#include <QItemSelectionModel>
#include <QSqlQuery>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlRecord>
#include "chelperclass.h"
#include <QDesktopWidget>



QKalkulacijaKorekcija::QKalkulacijaKorekcija(QWidget *parent)
	: QMyBaseFormWidget(parent)
    ,selRow(-1)
    ,textId("")
    ,komintentID("")
    ,artikal_id(0)
    ,pItemDelegate(0)
    ,editorOpen(0)
	,m_sumaIznosStavki(0)
	,m_sumaTrosoci(0)
	,isKomintent(true)
{
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
	ui.lineEdit->setFocus();
	ui.lineEdit->setStyleSheet("background-color: yellow");
	ui.lineEdit->setText("");
	ui.lineEdit_2->setText("");

	ui.lineEdit->installEventFilter(this);
	ui.lineEdit_2->installEventFilter(this);
	ui.lineEdit_3->installEventFilter(this);
	ui.lineEdit_4->installEventFilter(this);
	ui.lineEdit_5->installEventFilter(this);
    ui.dateTimeEdit->installEventFilter(this);

	connect(ui.lineEdit, SIGNAL(returnPressed()), this, SLOT(on_pushButton_clicked1()));
	connect(ui.lineEdit_2, SIGNAL(returnPressed()), this, SLOT(on_pushButton_2_clicked()));
    connect(ui.lineEdit_3, SIGNAL(returnPressed()), this, SLOT(on_plineEdit3_Pressed()));
    connect(ui.lineEdit_4, SIGNAL(returnPressed()), this, SLOT(on_plineEdit4_Pressed()));
	connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(callImportPriemnici()));

	connect(ui.lineEdit_5, SIGNAL(editingFinished()), this, SLOT(updateModelData()));
	connect(ui.lineEdit_6, SIGNAL(editingFinished()), this, SLOT(updateModelData()));
	connect(ui.lineEdit_7, SIGNAL(editingFinished()), this, SLOT(updateModelData()));
	connect(ui.lineEdit_8, SIGNAL(editingFinished()), this, SLOT(updateModelData()));
	connect(ui.lineEdit_9, SIGNAL(editingFinished()), this, SLOT(updateModelData()));
	connect(ui.lineEdit_17, SIGNAL(editingFinished()), this, SLOT(updateModelData()));

	connect(ui.comboBox, SIGNAL(currentIndexChanged (const QString &)), this, SLOT(comboBoxChanged(const QString &)));

	connect(ui.lineEdit_13, SIGNAL(returnPressed()), this, SLOT(on_pushButton1_prevoznik()));

    pItemDelegate = new QSTableWidgetDelegate(ui.tableView);
    connect(this ,SIGNAL(editCell()),this,SLOT(openEditor()));
    connect(this ,SIGNAL(closeCell()),this,SLOT(closeEditor()));

    ui.tableView->setEditTriggers(QAbstractItemView::CurrentChanged);
    ui.tableView->setItemDelegate(pItemDelegate);

	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));


    model = new QStandardItemModel(0,11);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
    model->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм"));
    model->setHeaderData( 4, Qt::Horizontal, trUtf8("Реф."));
    model->setHeaderData( 5, Qt::Horizontal, trUtf8("Катал. број"));
    model->setHeaderData( 6, Qt::Horizontal, trUtf8("Цена"));
    model->setHeaderData( 7, Qt::Horizontal, trUtf8("Количина"));
	model->setHeaderData( 8, Qt::Horizontal, trUtf8("Трошоци"));
	model->setHeaderData( 9, Qt::Horizontal, trUtf8("Износ вал."));
	model->setHeaderData( 10, Qt::Horizontal, trUtf8("Приемн. бр."));

    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
	ui.tableView->setHorizontalHeader(header);
    header->show();
}

QKalkulacijaKorekcija::~QKalkulacijaKorekcija()
{

}

void QKalkulacijaKorekcija::pressEscape()
{
	emit closeW();
}

void QKalkulacijaKorekcija::on_pushButton_clicked1()
{
	CHelperClass hclass(this);
    if (!hclass.isKomintentExists(ui.lineEdit->text()))
    {
        emit scallKomintenti((QWidget*)this, ui.lineEdit->text());
    }
    else
    {
        ui.lineEdit_14->setFocus();
    }
}

void QKalkulacijaKorekcija::on_pushButton1_prevoznik()
{
	isKomintent = false;
	CHelperClass hclass(this);
	if (!hclass.isKomintentExists(ui.lineEdit_13->text()))
	{
		emit scallKomintenti((QWidget*)this, ui.lineEdit_13->text());
	}
	else
	{
		ui.lineEdit_15->setFocus();
	}
}

void QKalkulacijaKorekcija::setFocusLine()
{
	if (isKomintent == true)
	{
		ui.lineEdit->setFocus();
	} 
	else
	{
		ui.lineEdit_13->setFocus();
	}
}

void QKalkulacijaKorekcija::setKomintent(QString text, QString textName)
{
	if (isKomintent == true)
	{
		ui.lineEdit->setText(textName);
		komintentID = text;
	} 
	else
	{
		ui.lineEdit_13->setText(textName);
		prevoznikID = text;
	}
}

void QKalkulacijaKorekcija::setArtikli(QString text, QString textName)
{
    ui.lineEdit_2->setText(textName);
    textId = text;
    artikal_id = text.toInt();

    QSqlQuery query;
    query.prepare("select art_nabavna_cena from artikli where id = :id");
    query.bindValue(":id", artikal_id);	
    query.exec();
    query.next();
    ui.lineEdit_3->setText(query.value(0).toString());
}

void QKalkulacijaKorekcija::setFocusLine2()
{
	ui.lineEdit_2->setFocus();
}

void QKalkulacijaKorekcija::on_pushButton_2_clicked()
{
    CHelperClass hclass(this);
    if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
    {
        emit scallArtikli((QWidget*)this, ui.lineEdit_2->text());
    }
    else
    {
        ui.lineEdit_4->setFocus();
    }
}
void QKalkulacijaKorekcija::on_pushButton_3_clicked()
{
    CHelperClass hclass(this);
    if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
    {
        QMessageBox msgBox;
        msgBox.setText(trUtf8("Податокот за артикал е невалиден\nОдбери артикал од листата на артикли!"));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.exec();
        ui.lineEdit_2->setFocus();
        return;
    }


    QLocale loc;
    if(textId.toInt() == -1)
    {
        return;
    }

	float kurs = ui.lineEdit_9->text().toFloat();
	float vkIznosFaktura = ui.lineEdit_10->text().toFloat();

	float carina = ui.lineEdit_6->text().toFloat();
	float transport = ui.lineEdit_7->text().toFloat();
	float drTrosoci = ui.lineEdit_8->text().toFloat();

	float vkIznosTrosoci = carina + transport + drTrosoci;
	float raspTrosoci = 0;
	if (vkIznosFaktura * kurs)
	{
		raspTrosoci = (vkIznosFaktura * kurs + vkIznosTrosoci)/(vkIznosFaktura * kurs);
	}

    //m_id = textId.toInt();

    QString temp = "select id, sifra, artikal, edm from artikli where id =";
    temp += textId;
    QSqlQuery query(temp);
    QString country1 = "";
    QString country2 = "";
    QString country3 = "";
    QString country4 = "";
    QString magacinTip = "";
    while (query.next()) {
        country1 = query.value(query.record().indexOf("id")).toString();
        country2 = query.value(query.record().indexOf("sifra")).toString();
        country3 = query.value(query.record().indexOf("artikal")).toString();
        country4 = query.value(query.record().indexOf("edm")).toString();
        //        ui.lineEdit->setText(country1);
    }

    int row = model->rowCount();

    QStandardItem *item = new QStandardItem(country1);
    item->setEditable(false);
    ui.tableView->setRowHeight(row, 18);
    ui.tableView->setColumnWidth(0, 40);
    model->setItem(row, 0, item);

    item = new QStandardItem(country2);
    item->setEditable(false);
    ui.tableView->setRowHeight(row, 18);
    ui.tableView->setColumnWidth(1, 70);
    model->setItem(row, 1, item);

    item = new QStandardItem(country3);
    item->setEditable(false);
    ui.tableView->setRowHeight(row, 18);
    ui.tableView->setColumnWidth(2, 220);
    model->setItem(row, 2, item);

    item = new QStandardItem(country4);
    item->setEditable(false);
    ui.tableView->setRowHeight(row, 18);
    ui.tableView->setColumnWidth(3, 60);
    model->setItem(row, 3, item);


    item = new QStandardItem(loc.toString(ui.lineEdit_4->text().toFloat(), 'f', 2));
    item->setTextAlignment(Qt::AlignRight);
    item->setEditable(false);
    ui.tableView->setRowHeight(row, 18);
    ui.tableView->setColumnWidth(4, 80);
    model->setItem(row, 4, item);

    item = new QStandardItem(loc.toString(ui.lineEdit_3->text().toFloat(), 'f', 2));
    item->setTextAlignment(Qt::AlignRight);
    item->setEditable(false);
    ui.tableView->setRowHeight(row, 18);
    ui.tableView->setColumnWidth(5, 80);
    model->setItem(row, 5, item);

	item = new QStandardItem(loc.toString(ui.lineEdit_3->text().toFloat() * kurs, 'f', 2));
    item->setTextAlignment(Qt::AlignRight);
    item->setEditable(false);
    ui.tableView->setRowHeight(row, 18);
    ui.tableView->setColumnWidth(6, 80);
    model->setItem(row, 6, item);

	item = new QStandardItem(loc.toString(ui.lineEdit_3->text().toFloat() * kurs * raspTrosoci, 'f', 2));
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(7, 80);
	model->setItem(row, 7, item);

	item = new QStandardItem(loc.toString(ui.lineEdit_4->text().toFloat() * ui.lineEdit_3->text().toFloat() * kurs * (raspTrosoci - 1), 'f', 2));
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(7, 80);
	model->setItem(row, 8, item);

	item = new QStandardItem(loc.toString(ui.lineEdit_4->text().toFloat() * ui.lineEdit_3->text().toFloat(), 'f', 2));
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(7, 80);
	model->setItem(row, 9, item);

    QItemSelectionModel *sm = ui.tableView->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();

	ui.lineEdit_2->setText("");
    ui.lineEdit_3->setText("");
    ui.lineEdit_4->setText("");
    ui.lineEdit_2->setFocus();
    textId = "-1";
}

void QKalkulacijaKorekcija::selectionChanged(QModelIndex modelX,QModelIndex modelY)
{
	selRow = modelX.row();
	editorOpen = false;
	emit closeCell();
}

void QKalkulacijaKorekcija::on_pushButton_6_clicked()
{
	model->removeRow(selRow);
}
void QKalkulacijaKorekcija::pressReturn()
{
    if (ui.pushButton_3->hasFocus())
    {
        on_pushButton_3_clicked();
    }
    else if (ui.pushButton_6->hasFocus())
    {
        on_pushButton_6_clicked();
    }
    else if (ui.tableView->hasFocus())
    {
        if (editorOpen)
        {
            emit closeCell();
			editorOpen = false;
        }
        else
        {
            emit editCell();
			editorOpen = true;
        }
    }
}
void QKalkulacijaKorekcija::init(int id)
{
	QLocale loc;
    if(id == -1)
	{
		return;
	}

	m_id = id;
    ui.lineEdit_16->setText(QString::number(id, 10));
    QString temp1 = 
        "select kalkulacii.id, komintenti.id , komintenti.naziv, kalkulacii.datum , dok_opis, carina, transport, drugi_trosoci, iznos_faktura, kurs, valuta, danok, broj_orig_fakt, orig_fakt_datum, prevoznik_id, prev_fakt_br,prev_fakt_datum, kalkulacii.rabat "
        "from kalkulacii " 
        "left join komintenti on kalkulacii.komintent_id = komintenti.id "
        "where  kalkulacii.dok_id = ";        
    temp1 += QString::number(id, 10);
    QSqlQuery query1(temp1);
    while (query1.next())
    {
        ui.lineEdit->setText(query1.value(2).toString().isEmpty() ? "" : query1.value(2).toString());
        komintentID = query1.value(1).toString();
        dokumentID = query1.value(0).toString();
        QString a = query1.value(0).toString();
		ui.dateTimeEdit->setDate(query1.value(3).toDate());
        ui.textEdit->setPlainText(query1.value(4).toString());
		ui.lineEdit_6->setText(query1.value(5).toString());
		ui.lineEdit_7->setText(query1.value(6).toString());
		ui.lineEdit_8->setText(query1.value(7).toString());
		ui.lineEdit_5->setText(query1.value(8).toString());
		ui.lineEdit_9->setText(query1.value(9).toString());
		ui.comboBox->setEditText(query1.value(10).toString());
		ui.lineEdit_10->setText(query1.value(11).toString());
	
		ui.lineEdit_14->setText(query1.value(12).toString());
		ui.dateTimeEdit_2->setDate(query1.value(13).toDate());
		prevoznikID = query1.value(14).toString();
		CHelperClass hlp(this);
		ui.lineEdit_13->setText(hlp.getKomintentName(prevoznikID));
		ui.lineEdit_15->setText(query1.value(15).toString());
		ui.dateTimeEdit_3->setDate(query1.value(16).toDate());
		ui.lineEdit_17->setText(query1.value(17).toString());
    }

	float kurs = ui.lineEdit_9->text().toFloat();
	float vkIznosFaktura = ui.lineEdit_5->text().toFloat();

	float carina = ui.lineEdit_6->text().toFloat();
	float transport = ui.lineEdit_7->text().toFloat();
	float drTrosoci = ui.lineEdit_8->text().toFloat();
	float rabat = ui.lineEdit_17->text().toFloat();
	float kRabD = (100.f - rabat) / 100.f;
	float vkIznosTrosoci = carina + transport + drTrosoci;
	float raspTrosoci = 0;
	if (vkIznosFaktura * kurs)
	{
		raspTrosoci = (vkIznosFaktura * kurs * kRabD + vkIznosTrosoci)/(vkIznosFaktura * kurs * kRabD);
	}

    int r = 0;
    int c = 11;
    int fieldNo[11];
    QString country[11];
    int colWidth[] = {40, 70, 220, 60, 80, 80, 80, 80, 80, 80, 80};
    QString colName[] = {"id", "sifra", "artikal", "edm", "ikol", "icena", "mag_id", "priemnica_br" };
    QString temp = 
        "select artikli.id, sifra, artikal, edm, ikol, icena, priemnica_br "
        "from kalkulacii_stavki "
        "left join artikli on kalkulacii_stavki.artikal_id=artikli.id "
        "where  kalkulacii_stavki.dok_id= ";
    temp += QString::number(id, 10);
    QSqlQuery query(temp);
    model = new QStandardItemModel(r,c);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
    model->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм."));
    model->setHeaderData( 4, Qt::Horizontal, trUtf8("Количина"));
    model->setHeaderData( 5, Qt::Horizontal, trUtf8("E.Цена.Вал."));
    model->setHeaderData( 6, Qt::Horizontal, trUtf8("E.Цена.Ден."));
	model->setHeaderData( 7, Qt::Horizontal, trUtf8("E.Трошоци"));
	model->setHeaderData( 8, Qt::Horizontal, trUtf8("E.Наб.Цена"));
	model->setHeaderData( 9, Qt::Horizontal, trUtf8("Вк.Износ."));
	model->setHeaderData( 10, Qt::Horizontal, trUtf8("Приемн. бр."));
    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
    ui.tableView->setHorizontalHeader(header);
    header->show();
    int row = 0;
	m_sumaIznosStavki = 0;
	m_sumaTrosoci = 0;
	while (query.next()) 
	{
		int row = model->rowCount();
		for (int i = 0; i < c; i++)
		{
			QStandardItem *item = NULL;
			QString temp = "";

			if ((i > 3) && (i < 6))
			{
				temp = query.value(i).toString();
				temp =  loc.toString(temp.toFloat(), 'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else if(i <= 3)
			{
				temp = query.value(i).toString();
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignLeft);
			}
			else 
			{
				if (i == 6)
				{
					temp = query.value(5).toString();
					temp =  loc.toString(temp.toFloat() * kurs * kRabD, 'f', 2);
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
				if (i == 7)
				{
					temp =  loc.toString( query.value(5).toFloat() * kurs * kRabD * (raspTrosoci - 1), 'f', 2);
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}

				if (i == 8)
				{
					temp = query.value(5).toString();
					temp =  loc.toString(temp.toFloat()  * kurs * kRabD * raspTrosoci, 'f', 2);
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
				if (i == 9)
				{
					temp =  loc.toString(query.value(4).toFloat() * query.value(5).toFloat() * kurs * kRabD * raspTrosoci, 'f', 2); // kol * cena vo valuta
					m_sumaIznosStavki += query.value(4).toFloat() * query.value(5).toFloat() * kurs * kRabD * raspTrosoci;
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
				if (i == 10)
				{
					temp =  query.value(6).toString(); // priemnica br.
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
			}
// 			ui.lineEdit_12->setText(loc.toString( m_sumaIznosStavki, 'f', 2));
// 			ui.lineEdit_13->setText(loc.toString( m_sumaTrosoci, 'f', 2));

			item->setEditable(false);
			ui.tableView->setRowHeight(row, 18);
			ui.tableView->setColumnWidth(i, colWidth[i]);
			model->setItem(row, i, item);
		}        
	} 
	updateModelData();
	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();
	ui.lineEdit->setFocus();
}

void QKalkulacijaKorekcija::on_pushButton_5_clicked()
{
	pressEscape();
}

void QKalkulacijaKorekcija::pressF9()
{
	on_pushButton_4_clicked();
}


void QKalkulacijaKorekcija::on_pushButton_4_clicked()
{
		QLocale loc;
		if (!validateKomintent())
		{
			QMessageBox msgBox;
			msgBox.setText(trUtf8("Податокот за коминтент е невалиден\nОдбери коминтент од листата на коминтенти!"));
			msgBox.setStandardButtons(QMessageBox::Ok);
			msgBox.setDefaultButton(QMessageBox::Ok);
			msgBox.exec();
			ui.lineEdit->setFocus();
			return;
		}

		int mmid = m_id;
        int cols = model->columnCount();
        int rows = model->rowCount();
        if (!rows)
        {
            return;
        }

        int mid=0;
		QSqlDatabase db = QSqlDatabase::database();
		db.transaction();	
		bool sqlStat = true;
		
		QSqlQuery query1;
        query1.clear();
        query1.prepare("update kalkulacii set dok_id = :a0, datum=:a1, komintent_id=:a2 , dok_opis = :a3, carina = :a5, transport = :a6, drugi_trosoci = :a7, iznos_faktura = :a8, kurs = :a9, valuta = :a10, danok = :a11, broj_orig_fakt = :a12, orig_fakt_datum = :a13, prevoznik_id = :a14, prev_fakt_br = :a15, prev_fakt_datum = :a16, rabat = :a17 where id=:aid ");
		
		query1.bindValue(":a0", ui.lineEdit_16->text());	
        query1.bindValue(":a1", ui.dateTimeEdit->dateTime());	
        query1.bindValue(":a2", komintentID);	
        query1.bindValue(":a3", ui.textEdit->toPlainText());	
        query1.bindValue(":aid", dokumentID);	
		query1.bindValue(":a5", ui.lineEdit_6->text());
		query1.bindValue(":a6", ui.lineEdit_7->text());
		query1.bindValue(":a7", ui.lineEdit_8->text());
		query1.bindValue(":a8", ui.lineEdit_5->text());
		query1.bindValue(":a9", ui.lineEdit_9->text());
		query1.bindValue(":a10", ui.comboBox->currentText());
		query1.bindValue(":a11", ui.lineEdit_10->text());

		query1.bindValue(":a12", ui.lineEdit_14->text());
		query1.bindValue(":a13", ui.dateTimeEdit_2->date().toString("yyyy-MM-dd"));
		query1.bindValue(":a14", prevoznikID);
		query1.bindValue(":a15", ui.lineEdit_15->text());
		query1.bindValue(":a16", ui.dateTimeEdit_3->date().toString("yyyy-MM-dd"));
		query1.bindValue(":a17", ui.lineEdit_17->text());

		float kurs = ui.lineEdit_9->text().toFloat();
		float vkIznosFaktura = ui.lineEdit_10->text().toFloat();


		sqlStat = sqlStat && query1.exec();
		QSqlError err = query1.lastError();

        query1.clear();
        query1.prepare("delete from kalkulacii_stavki where dok_id = :a");
        query1.bindValue(":a", mmid);	
        sqlStat = sqlStat && query1.exec();
        QString temp = "select max(dok_id) from kalkulacii where dok_tip = 20";
        QSqlQuery query;
        for (int i = 0; i < rows; i++)
        {

            QString mTipDok = "P";
            QString mEmpty ="Empty";
            QString mArtikalID = model->item(i, 0)->text();
            QString mArtikalSifra = model->item(i, 1)->text();
            QString mArtikalNaziv = model->item(i, 2)->text();
            QString mArtikalEdm = model->item(i, 3)->text();
            QString mArtikalKolicina = model->item(i, 4)->text();
            QString mArtikalCena = model->item(i, 5)->text();
            QString mEdinNabCena = model->item(i, 8)->text();
			QString mPriemnicaBr = model->item(i, 10)->text();

			int mMagacinTip = model->item(i, 6)->text() == trUtf8("Артикли") ? 0 : 1;

            query.clear();
            query.prepare(
                "insert into kalkulacii_stavki(dok_id, artikal_id, ikol, icena, rabat, sub_tip, mag_id, priemnica_br) "
				"values(:a1,:a3,:a4,:a5,:a6,:a7,:a8,:a9)"
                );

            query.bindValue(":a1", ui.lineEdit_16->text());	
            query.bindValue(":a3", mArtikalID);	
            query.bindValue(":a4", loc.toFloat(mArtikalKolicina));	
            query.bindValue(":a5", loc.toFloat(mArtikalCena));	
            query.bindValue(":a6", 0);	
            query.bindValue(":a7", 0);	
            query.bindValue(":a8", mMagacinTip);
            query.bindValue(":a9", mPriemnicaBr);

            sqlStat = sqlStat && query.exec();
			
			query.clear();
            query.prepare(
				"update magacin SET icena = :a1 "
				"WHERE (magacin.dok_tip = 20 OR magacin.dok_tip = 24) AND artikal_id = :a2 AND magacin.dok_id=:a3 "
                );
			query.bindValue(":a3", loc.toInt(mPriemnicaBr));	
            query.bindValue(":a2", mArtikalID);	
            query.bindValue(":a1", loc.toFloat(mEdinNabCena));	
			sqlStat = sqlStat && query.exec();

            QSqlError err = query.lastError();
        }

		if (sqlStat)
		{
			db.commit();
			QMessageBox msgBox;
			msgBox.setText(trUtf8("Калкулацијата е успешно корегирана."));
			msgBox.setStandardButtons(QMessageBox::Ok);
			msgBox.setDefaultButton(QMessageBox::Ok);
			msgBox.exec();
			pressEscape();
		}
		else
		{
			db.rollback();
			QMessageBox msgBox;
			msgBox.setText(trUtf8("Калкулацијата НЕ Е корегирана !!!."));
			msgBox.setStandardButtons(QMessageBox::Ok);
			msgBox.setDefaultButton(QMessageBox::Ok);
			msgBox.exec();
		}
}

bool QKalkulacijaKorekcija::existDok(int idDok)
{
    int nCount = 0;
    QString temp = "select count(dok_id) br from kalkulacii where dok_id =";
    temp += QString::number(idDok, 10);
    QSqlQuery query(temp);
    QString country1 = "";
    int fieldNo = query.record().indexOf("br");
    while (query.next()) {
        nCount = query.value(0).toInt() + 1;
    }
    return nCount > 0 ? true : false;
}

bool QKalkulacijaKorekcija::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() == QEvent::FocusIn)
	{
		if (object == ui.lineEdit)
		{
			ui.lineEdit->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_2)
		{
			ui.lineEdit_2->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_3)
		{
			ui.lineEdit_3->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_4)
		{
			ui.lineEdit_4->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_5)
		{
			ui.lineEdit_5->setStyleSheet("background-color: yellow");
		}
        if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: yellow");
        }

	}
	if (event->type() == QEvent::FocusOut)
	{
		if (object == ui.lineEdit)
		{
			ui.lineEdit->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_2)
		{
			ui.lineEdit_2->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_3)
		{
			ui.lineEdit_3->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_4)
		{
			ui.lineEdit_4->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_5)
		{
			ui.lineEdit_5->setStyleSheet("background-color: none");
		}
        if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: none");
        }
	}

	return false;
}


void QKalkulacijaKorekcija::on_plineEdit3_Pressed()
{
    ui.lineEdit_4->setFocus();
}
void QKalkulacijaKorekcija::on_plineEdit4_Pressed()
{
    on_pushButton_3_clicked();
}
void QKalkulacijaKorekcija::openEditor()
{
	//	tableView->closePersistentEditor(indexPrev);
	QModelIndex index;
	QModelIndexList indexes = ui.tableView->selectionModel()->selection().indexes();
	index = indexes.at(0);	// To get the row/column numbers use 
	if (index.column() == 5)
	{
		ui.tableView->openPersistentEditor(index);
	}
	indexPrev = index;
}

void QKalkulacijaKorekcija::closeEditor()
{
	QModelIndex index;
	QModelIndexList indexes = ui.tableView->selectionModel()->selection().indexes();
	if (indexes.isEmpty())
	{
		return;
	}
	else
	{
		index = indexes.at(0);	// To get the row/column numbers use 
		if (index.column() != 5)
		{
			return;
		}
	}
	QLocale loc;

	float kurs = ui.lineEdit_9->text().toFloat();
	float vkIznosFaktura = ui.lineEdit_5->text().toFloat();

	float carina = ui.lineEdit_6->text().toFloat();
	float transport = ui.lineEdit_7->text().toFloat();
	float drTrosoci = ui.lineEdit_8->text().toFloat();


	float vkIznosTrosoci = carina + transport + drTrosoci;
	float raspTrosoci = 0;
	if (vkIznosFaktura * kurs)
	{
		raspTrosoci = (vkIznosFaktura * kurs + vkIznosTrosoci)/(vkIznosFaktura * kurs);
	}


	ui.tableView->closePersistentEditor(indexPrev);
	QStandardItem *tempOrig = model->item(indexPrev.row(), indexPrev.column());
	QStandardItem *tempOrigKol = model->item(indexPrev.row(), indexPrev.column()-1);
	QStandardItem *temp = model->item(indexPrev.row(), indexPrev.column() + 1);
	if(temp)
	{
		QString valueTemp = tempOrig->text();
		valueTemp =  loc.toString(valueTemp.toFloat() * kurs , 'f', 2);
		temp->setText(valueTemp);
	}
	temp = model->item(indexPrev.row(), indexPrev.column() + 2);
	if(temp)
	{
		QString valueTemp = tempOrig->text();
		valueTemp =  loc.toString(valueTemp.toFloat() * kurs * (raspTrosoci - 1), 'f', 2);
		temp->setText(valueTemp);
	}

	temp = model->item(indexPrev.row(), indexPrev.column() + 3);
	if(temp)
	{
		QString valueTemp = tempOrig->text();
		valueTemp =  loc.toString(valueTemp.toFloat() * kurs * raspTrosoci , 'f', 2);
		temp->setText(valueTemp);
	}
	temp = model->item(indexPrev.row(), indexPrev.column() + 4);
	if(temp)
	{
		QString valueTemp = tempOrig->text();
		QString valueTempKol = tempOrigKol->text();

		valueTemp =  loc.toString(valueTemp.toFloat() * valueTempKol.toFloat() * kurs * raspTrosoci, 'f', 2);
		temp->setText(valueTemp);
	}
	updateModelData();
}

bool QKalkulacijaKorekcija::validateKomintent()
{
	bool stat = false;
	CHelperClass hclass(this);
	if (hclass.isKomintentExists(ui.lineEdit->text()))
	{
		stat = true;
	}
	return stat;
}
void QKalkulacijaKorekcija::callImportPriemnici()
{
	emit scallPriemnici((QWidget*)this, ui.lineEdit->text());
}

void QKalkulacijaKorekcija::setPriemnicaID(QString text, QString textName)
{
	QLocale loc;

	float kurs = ui.lineEdit_9->text().toFloat();
	float vkIznosFaktura = ui.lineEdit_5->text().toFloat();

	float carina = ui.lineEdit_6->text().toFloat();
	float transport = ui.lineEdit_7->text().toFloat();
	float drTrosoci = ui.lineEdit_8->text().toFloat();

	float vkIznosTrosoci = carina + transport + drTrosoci;
	float raspTrosoci = 0;
	if (vkIznosFaktura * kurs)
	{
		raspTrosoci = (vkIznosFaktura * kurs + vkIznosTrosoci)/(vkIznosFaktura * kurs);
	}

	int m_id = text.toInt();
	int id = m_id;
	if(m_id == -1)
	{
		return;
	}
	int r = 0;
	int c = 11;
	int fieldNo[10];
	QString country[10];
	int colWidth[] = {40, 70, 220, 60, 80, 80, 80, 80, 80, 80};
	QString colName[] = {"id", "sifra", "artikal", "edm", "ikol", "icena", "mag_id" };
	QString temp = 
		"select artikli.id, sifra, artikal, edm, ikol, icena "
		"from magacin "
		"left join artikli on magacin.artikal_id=artikli.id "
		"where (magacin.dok_tip = 20 or magacin.dok_tip = 24) and magacin.dok_id= ";
	temp += QString::number(id, 10);
	QSqlQuery query(temp);
	/*	model = new QStandardItemModel(r,c);*/
	model->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
	model->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
	model->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
	model->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм."));
	model->setHeaderData( 4, Qt::Horizontal, trUtf8("Количина"));
	model->setHeaderData( 5, Qt::Horizontal, trUtf8("Е.Цена.Вал."));
	model->setHeaderData( 6, Qt::Horizontal, trUtf8("Е.Цена.Ден."));
	model->setHeaderData( 7, Qt::Horizontal, trUtf8("Е.Наб.Цена "));
	model->setHeaderData( 8, Qt::Horizontal, trUtf8("Е.Трошоци "));
	model->setHeaderData( 9, Qt::Horizontal, trUtf8("Вк.Износ "));
	model->setHeaderData( 10, Qt::Horizontal, trUtf8("Приемн. бр."));

	ui.tableView->setModel(model);
	header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
	ui.tableView->setHorizontalHeader(header);
	header->show();
	//	int row = 0;
	while (query.next()) 
	{
		int row = model->rowCount();
		for (int i = 0; i < c; i++)
		{
			QStandardItem *item = NULL;
			QString temp = "";

			if ((i > 3) && (i < 6))
			{
				temp = query.value(i).toString();
				temp =  loc.toString(temp.toFloat(), 'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else if(i <= 3)
			{
				temp = query.value(i).toString();
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignLeft);
			}
			else 
			{
				if (i == 6)
				{
					temp = query.value(5).toString();
					temp =  loc.toString(temp.toFloat() * kurs , 'f', 2);
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
				if (i == 7)
				{
					temp =  loc.toString( query.value(5).toFloat() * kurs * (raspTrosoci - 1), 'f', 2);
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
				if (i == 8)
				{
					temp =  loc.toString( query.value(5).toFloat() * kurs * raspTrosoci, 'f', 2); // kol * cena vo valuta
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
				if (i == 9)
				{
					temp =  loc.toString(query.value(4).toFloat() * query.value(5).toFloat() * kurs * raspTrosoci, 'f', 2); // kol * cena vo valuta
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
				if (i == 10)
				{
					item = new QStandardItem(text);
					item->setTextAlignment(Qt::AlignRight);
				}
			}

			item->setEditable(false);
			ui.tableView->setRowHeight(row, 18);
			ui.tableView->setColumnWidth(i, colWidth[i]);
			model->setItem(row, i, item);
		}        
	} 
	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();
	ui.lineEdit->setFocus();
}

void QKalkulacijaKorekcija::comboBoxChanged(const QString & str)
{
	ui.lineEdit_9->selectAll();
	ui.lineEdit_9->setFocus();
}

void QKalkulacijaKorekcija::updateModelData()
{
	QLocale loc;
	float rabatDevizi = ui.lineEdit_17->text().toFloat();
	float kRabD = 1.f - rabatDevizi / 100.f;

	float kurs = ui.lineEdit_9->text().toFloat();
	float vkIznosFaktura = ui.lineEdit_5->text().toFloat();
	vkIznosFaktura = vkIznosFaktura * kRabD;
	float carina = ui.lineEdit_6->text().toFloat();
	float transport = ui.lineEdit_7->text().toFloat();
	float drTrosoci = ui.lineEdit_8->text().toFloat();

	float vkIznosTrosoci = carina + transport + drTrosoci;
	float raspTrosoci = 0;
	if (vkIznosFaktura * kurs)
	{
		raspTrosoci = (vkIznosFaktura * kurs + vkIznosTrosoci)/(vkIznosFaktura * kurs);
	}
	m_sumaIznosStavki = 0;
	m_sumaTrosoci = 0;
	for (int r = 0; r < model->rowCount(); r++)
	{
		QStandardItem *tempOrigKol = model->item(r, 4);
		QStandardItem *tempOrig = model->item(r, 5);
		QStandardItem *temp = model->item(r, 6);
		if(temp)
		{
			QString valueTemp = tempOrig->text();
			valueTemp =  loc.toString(loc.toFloat(valueTemp) * kurs * kRabD, 'f', 2);
			temp->setText(valueTemp);
		}
		temp = model->item(r, 7);
		if(temp)
		{
			QString valueTempKol = tempOrigKol->text();
			QString valueTemp = tempOrig->text();
			valueTemp =  loc.toString(loc.toFloat(valueTemp) * kurs * kRabD * (raspTrosoci-1) , 'f', 2);
			m_sumaTrosoci += loc.toFloat(valueTemp);
			temp->setText(valueTemp);
		}

		temp = model->item(r, 8);
		if(temp)
		{
			QString valueTemp = tempOrig->text();
			valueTemp =  loc.toString(loc.toFloat(valueTemp) * kurs * kRabD * raspTrosoci , 'f', 2);
			temp->setText(valueTemp);
		}
		temp = model->item(r, 9);
		if(temp)
		{
			QString valueTempKol = tempOrigKol->text();
			QString valueTemp = tempOrig->text();
			valueTemp =  loc.toString(loc.toFloat(valueTemp) * loc.toFloat(valueTempKol) * kurs * kRabD * raspTrosoci , 'f', 2);
			m_sumaIznosStavki += loc.toFloat(valueTemp);
			temp->setText(valueTemp);
		}
	}
	ui.lineEdit_11->setText(loc.toString( m_sumaIznosStavki, 'f', 2));
	ui.lineEdit_12->setText(loc.toString( vkIznosFaktura * kurs + carina + transport + drTrosoci, 'f', 2));

}

